import { Component, OnInit, OnChanges, Input, Output, EventEmitter, SimpleChanges, OnDestroy } from '@angular/core';
import { MatDialog } from '@angular/material';
import { RestService } from '../../services/rest.service';
import { TranslateService } from '@ngx-translate/core';
import { AlarmDialogComponent } from '../alarm-dialog/alarm-dialog.component';
import { BhhistDialogComponent } from '../bhhist-dialog/bhhist-dialog.component';
import { PersonContentComponent } from '../person-content/person-content.component';
import { environment } from 'environments/environment';

import * as _ from 'lodash';

const BEDLINK = ' ';

@Component({
  selector: 'app-bandobject',
  templateUrl: './bandobject.component.html',
  styleUrls: ['./bandobject.component.css']
})
export class BandobjectComponent implements OnInit, OnChanges, OnDestroy {
  refreshInterval = environment.interval;
  institution: any;
  interval;
  options: any;

  bChartOptions;
  bEchartsInstance;
  bTitle;

  hChartOptions;
  hEchartsInstance;
  hTitle;

  pChartOptions;
  pEchartsInstance;
  pTitle;

  sChartOptions;
  sEchartsInstance;
  sTitle;

  awayAlarm = '-';
  sideAlarm = '-';
  breatheAlarm = '-';
  heartAlarm = '-';
  wetAlarm = '-';

  bedNumber = '';
  building = '';
/*
  maxHeart: any;
  maxHeartTime: any;
  maxHv: any;
  maxHvTime: any;
  maxLv: any;
  maxLvTime: any;
  meanHeart: any;
  meanHv: any;
  meanLv: any;
  minHeart: any;
  minHeartTime: any;
  minHv: any;
  minHvTime: any;
  minLv: any;
  minLvTime: any;
*/
  randomSugar=[];

  @Input() person: any;
  @Output() hide = new EventEmitter<any>();

  constructor(private rest: RestService, private translate: TranslateService, private dialog: MatDialog) {
    this.bTitle = this.translate.get('breathe')['value'];
    this.hTitle = this.translate.get('heart')['value'];
    this.pTitle = this.translate.get('pressure')['value'];
    this.sTitle = this.translate.get('sugar')['value'];
    //this.randomSugar = [6.1, 5.4, 7.2, 4.5, 8.7];
    for(var i=0;i<50;i++){
      this.randomSugar[i] = 6+Math.random();
    }
  }

  parseBedString(bedString) {
    if (!bedString) {
      this.bedNumber = '-';
      this.building = '-';
      return;
    }

    const beds = bedString.split('##');
    this.bedNumber = beds.pop();
    this.building = beds.join(BEDLINK);
  }

  hideIt() {
    if (this.interval) {
      clearInterval(this.interval);
    }

    this.hide.emit();
  }

  initChart() {
    this.bChartOptions = _.cloneDeep(this.options);
    this.bChartOptions.title.text = this.bTitle;
    this.bChartOptions.series[0].markLine.data = [
      {name: 'upper', yAxis: this.person.breatheUp},
      {name: 'lower', yAxis: this.person.breatheLow},
    ];

    this.hChartOptions = _.cloneDeep(this.options);
    this.hChartOptions.title.text = this.hTitle;
    this.hChartOptions.series[0].markLine.data = [
      {name: 'upper', yAxis: this.person.heartUp},
      {name: 'lower', yAxis: this.person.heartLow},
    ];

    this.options.title.subtext=this.translate.get('pressureUnit')['value']
    this.pChartOptions = _.cloneDeep(this.options);
    this.pChartOptions.title.text = this.pTitle;
   /* this.pChartOptions.series[0].markLine.data = [
      {name: 'upper', yAxis: this.person.heartUp},
      {name: 'lower', yAxis: this.person.heartLow},
    ];*/
    this.pChartOptions.tooltip ={
        trigger: 'axis',
        formatter: (params) => {
          return new Date(params[0].data[0]).toLocaleString() + '<br>' + params[1].data[1] + '-'+params[0].data[1]+'  ' + this.translate.get('pressureUnit')['value'];
        }
      };

    this.options.title.subtext=this.translate.get('sugarUnit')['value']
    this.sChartOptions = _.cloneDeep(this.options);
    this.sChartOptions.title.text = this.sTitle;
    this.sChartOptions.tooltip= {
      trigger: 'axis',
        formatter: (params) => {
        return new Date(params[0].data[0]).toLocaleString() + '<br>' + params[0].data[1]+'  ' + this.translate.get('sugarUnit')['value'];
      }
    };
   /* this.sChartOptions.series[0].markLine.data = [
      {name: 'upper', yAxis: this.person.heartUp},
      {name: 'lower', yAxis: this.person.heartLow},
    ];*/
  }

  onBChartInit(ec) {
    this.bEchartsInstance = ec;
    ec.setOption(this.bChartOptions);
  }

  onHChartInit(ec) {
    this.hEchartsInstance = ec;
    ec.setOption(this.hChartOptions);
  }

  onPChartInit(ec) {
    this.pEchartsInstance = ec;
    ec.setOption(this.pChartOptions);
  }

  onSChartInit(ec) {
    this.sEchartsInstance = ec;
    ec.setOption(this.sChartOptions);
  }
  startRoutine() {
    this.initData();
    this.interval = setInterval(() => {
      this.initData();
    }, this.refreshInterval);
  }

  getSecondsFromLast8Am() {
    let hour = new Date().getHours();
    hour = hour >= 8 ? (hour - 8) : (24 + hour - 8);
    return hour * 60 * 60 + new Date().getMinutes() * 60 + new Date().getSeconds() - 1;
  }

  buildEmptyData(startTime, endTime, step) {
    const data = [[startTime * 1000, ''], [endTime * 1000, '']];
    return data;
  }
  add0(m){return m<10?'0'+m:m }
  dateformat(date)
  {
//shijianchuo是整数，否则要parseInt转换
    var time = new Date(date);
    //var y = time.getFullYear();
    var m = time.getMonth()+1;
    var d = time.getDate();
    var h = time.getHours();
    var mm = time.getMinutes();
    // var s = time.getSeconds();
    //return this.add0(m)+'-'+this.add0(d)+' '+this.add0(h)+':'+this.add0(mm);//+':'+add0(s);
    return m+'-'+d+' '+h+':'+mm;//+':'+add0(s);
  }
  initData() {
    const bendTime = new Date().getTime() ;/// 1000;
    const bstartTime = bendTime - 12 *60 * 60*1000;
    const bstep = 5;
    // https://192.168.123.235/api/influx/getHeartHistory?devId=9510515034&start=1559529341000&end=1559615741000

    this.rest.getWithParams('api/influx/getHeartHistory', {
      //personId: this.person.id,
      devId:this.person.device2Id,//9510515034,
      start: bstartTime,//1559529341000,//
      end: bendTime,//1559615741000,//endTime,
      step: bstep,
      timeout: 4
    }).subscribe(resp => {
      let sData = resp;
      let pData =[];
      for (const key in sData) {
        if (sData.hasOwnProperty(key)) {
          const a = sData[key];
          pData.push(a);
        }
      }
      let heartData =[];
      let pressureHData = [];
      let pressureLData = [];
      let sugarData= [];
      for(var i=0;i<pData.length;i++){
        let tmpData = [];
        tmpData[0] = pData[i][0];
        tmpData[1] = pData[i][2];
        heartData.push(tmpData);
        let tmppData=[];
        tmppData[0] = pData[i][0];
        tmppData[1] = pData[i][3];
        pressureHData.push(tmppData);
        let tmplData=[];
        tmplData[0] = pData[i][0];
        tmplData[1] = pData[i][4];
        pressureLData.push(tmplData);
        let tmpsData = [];
        tmpsData[0] = pData[i][0];
        let tmpsugar = 0.0;
        tmpsugar = Number(this.randomSugar[i]);
        tmpsData[1] = tmpsugar.toFixed(1);
        sugarData.push(tmpsData);
      }

      if (heartData.length < 1){
        this.hChartOptions.title.text = this.bTitle;
        this.hChartOptions.title.textStyle.color = 'darkblue';
        this.hChartOptions.series[0].data = this.buildEmptyData(startTime, endTime, step);
        this.hEchartsInstance.setOption(this.hChartOptions);
        return;
      }

      /* const data =  heartData;//['data']['result'][0].values;
       data.forEach(item => {
         console.log(item);
         item[0] = item[0] ;//* 1000;
       });*/
      this.hChartOptions.series[0].data = heartData;
      let currentValue = heartData[0][1];
      if (currentValue.length === 1) {
        currentValue = '0' + currentValue;
      }
      this.hChartOptions.title.text = this.hTitle + ' ' + currentValue;
      currentValue = _.toNumber(currentValue);
      if (currentValue < this.person.heartLow || currentValue > this.person.heartUp) {
        this.hChartOptions.title.textStyle.color = 'darkred';
      } else {
        this.hChartOptions.title.textStyle.color = 'darkgreen';
      }
      this.hEchartsInstance.setOption(this.hChartOptions);

      this.pChartOptions.series[0].data = pressureHData;
      this.pChartOptions.series[1].data = pressureLData;
      currentValue = pressureHData[0][1];
      if (currentValue.length === 1) {
        currentValue = '0' + currentValue;
      }
      this.pChartOptions.title.text = this.pTitle + ' ' + currentValue;
      currentValue = _.toNumber(currentValue);
      /*if (currentValue < this.person.heartLow || currentValue > this.person.heartUp) {
        this.hChartOptions.title.textStyle.color = 'darkred';
      } else {
        this.hChartOptions.title.textStyle.color = 'darkgreen';
      }*/
      this.pEchartsInstance.setOption(this.pChartOptions);

      this.sChartOptions.series[0].data = sugarData;
      currentValue = sugarData[0][1];
      if (currentValue.length === 1) {
        currentValue = '0' + currentValue;
      }
      this.sChartOptions.title.text = this.sTitle + ' ' + currentValue;
      currentValue = _.toNumber(currentValue);
    /*  if (currentValue < this.person.heartLow || currentValue > this.person.heartUp) {
        this.hChartOptions.title.textStyle.color = 'darkred';
      } else {
        this.hChartOptions.title.textStyle.color = 'darkgreen';
      }*/
      this.sEchartsInstance.setOption(this.sChartOptions);

    });

    const endTime = new Date().getTime() / 1000;
    const startTime = endTime - 60 * 60;
    const step = 5;
    this.rest.getWithParams('api/v1/query_range', {
      query: 'breathe{personId="' + this.person.id + '"}',
      start: startTime,
      end: endTime,
      step: step,
      timeout: 4
    }).subscribe(resp => {
      if (resp['status'] === 'success') {
        if (resp['data']['result'].length < 1) {
          this.bChartOptions.title.text = this.bTitle;
          this.bChartOptions.title.textStyle.color = 'darkblue';
          this.bChartOptions.series[0].data = this.buildEmptyData(startTime, endTime, step);
          this.bEchartsInstance.setOption(this.bChartOptions);
          return;
        }

        const data = resp['data']['result'][0].values;
        data.forEach(item => {
          item[0] = item[0] * 1000;
        });
        this.bChartOptions.series[0].data = data;
        let currentValue = data[data.length - 1][1];
        if (currentValue.length === 1) {
          currentValue = '0' + currentValue;
        }
        this.bChartOptions.title.text = this.bTitle + ' ' + currentValue;
        currentValue = _.toNumber(currentValue);
        if (currentValue < this.person.breatheLow || currentValue > this.person.breatheUp) {
          this.bChartOptions.title.textStyle.color = 'darkred';
        } else {
          this.bChartOptions.title.textStyle.color = 'darkgreen';
        }
        this.bEchartsInstance.setOption(this.bChartOptions);
      }
    });
/*
    this.rest.getWithParams('api/v1/query_range', {
      query: 'heart{personId="' + this.person.id + '"}',
      start: startTime,
      end: endTime,
      step: step,
      timeout: 4
    }).subscribe(resp => {
      if (resp['status'] === 'success') {
        if (resp['data']['result'].length < 1) {
          this.hChartOptions.title.text = this.hTitle;
          this.hChartOptions.title.textStyle.color = 'darkblue';
          this.hChartOptions.series[0].data = this.buildEmptyData(startTime, endTime, step);
          this.hEchartsInstance.setOption(this.hChartOptions);
          return;
        }

        const data = resp['data']['result'][0].values;
        data.forEach(item => {
          item[0] = item[0] * 1000;
        });
        this.hChartOptions.series[0].data = data;
        let currentValue = data[data.length - 1][1];
        if (currentValue.length === 1) {
          currentValue = '0' + currentValue;
        }
        this.hChartOptions.title.text = this.hTitle + ' ' + currentValue;
        currentValue = _.toNumber(currentValue);
        if (currentValue < this.person.heartLow || currentValue > this.person.heartUp) {
          this.hChartOptions.title.textStyle.color = 'darkred';
        } else {
          this.hChartOptions.title.textStyle.color = 'darkgreen';
        }
        this.hEchartsInstance.setOption(this.hChartOptions);
      }
    });
    */
    this.rest.getWithParams('api/pro/allAlarmCounters', {
      personId: this.person.id,
      interval: this.getSecondsFromLast8Am()
    }).subscribe(resp => {
      this.breatheAlarm = resp['breatheAlarm'];
      this.heartAlarm = resp['heartAlarm'];
      this.awayAlarm = resp['awayAlarm'];
      this.wetAlarm = resp['wetAlarm'];
      this.sideAlarm = resp['move'];
    });

    //api/influx/getHeartStatics?personId=6&start=1559964134000&end=1560136934000
    const weekendTime = new Date().getTime() ;
    const weekstartTime = weekendTime - 7* 24 * 60 * 60 * 1000;
    this.rest.getWithParams('api/influx/getHeartStatics', {
      personId: this.person.id,
      start: weekstartTime,
      end:weekendTime
    }).subscribe(resp => {
      if(resp!=null){
        this.person.maxHeart = resp['maxHeart'];
        this.person.maxHeartTime = this.dateformat(resp['maxHeartTime']);
        this.person.maxHv = resp['maxHv'];
        this.person.maxHvTime = this.dateformat(resp['maxHvTime']);
        this.person.maxLv = resp['maxLv'];
        this.person.maxLvTime = this.dateformat(resp['maxLvTime']);
        this.person.meanHeart = Number(resp['meanHeart']).toFixed(0);
        this.person.meanHv =  Number(resp['meanHv']).toFixed(0);
        this.person.meanLv =  Number(resp['meanLv']).toFixed(0);
        this.person.minHeart = resp['minHeart'];
        this.person.minHeartTime = this.dateformat(resp['minHeartTime']);
        this.person.minHv = resp['minHv'];
        this.person.minHvTime = this.dateformat(resp['minHvTime']);
        this.person.minLv = resp['minLv'];
        this.person.minLvTime = this.dateformat(resp['minLvTime']);
      }
    });
  }

  openAlarm(alarm) {
    this.dialog.open(AlarmDialogComponent, {
      disableClose: true,
      autoFocus: false,
      width: '800px',
      data: {
        person: this.person,
        alarm: alarm
      }
    });
  }

  openHistDialog() {
    this.dialog.open(BhhistDialogComponent, {
      disableClose: true,
      autoFocus: false,
      width: '1024px',
      data: {
        person: this.person
      }
    });
  }

  ngOnInit() {
    this.parseBedString(this.person.bedString);
    this.options = {
      title: {
        text: '',
        subtext: this.translate.get('heartUnit')['value'],
        subtextStyle: {color: 'black'},
        x: 'left',
        y: 'top',
        textStyle: {
          color: 'darkblue'
        },
      },
      tooltip: {
        trigger: 'axis',
        formatter: (params) => {
          return new Date(params[0].data[0]).toLocaleString() + '<br>' + params[0].data[1] + ' ' + this.translate.get('heartUnit')['value'];
        }
      },
      grid: {
        x: '80',
        y: '10',
        x2: '30',
        y2: '0',
        containLabel: true
      },
      xAxis: {
        type: 'time',
        splitLine: {
          show: true
        }
      },
      yAxis: {
        type : 'value',
        boundaryGap: false,
        splitLine: {
          show: true
        }
      },
      series: [{
        type: 'line',
        showSymbol: false,
        markLine: {
          itemStyle: {
            normal: {
              lineStyle: {
                type: 'dashed',
                color: 'darkred'
              }
            }
          },
          data: []
        },
        data: []
      },{
        type: 'line',
        showSymbol: false,
        markLine: {
          itemStyle: {
            normal: {
              lineStyle: {
                type: 'dashed',
                color: 'darkred'
              }
            }
          },
          data: []
        },
        data: []
      }]
    };

    this.initChart();

    setTimeout(() => {
      this.hEchartsInstance.resize();
      this.startRoutine();
    }, 100);
  }

  ngOnChanges(changes: SimpleChanges) {
    if (changes && changes.person && this.bEchartsInstance && this.hEchartsInstance) {
      // reinit the charts
      if (this.interval) {
        clearInterval(this.interval);
      }

      this.ngOnInit();
      this.bEchartsInstance.setOption(this.bChartOptions);
      this.hEchartsInstance.setOption(this.hChartOptions);
      this.pEchartsInstance.setOption(this.pChartOptions);
      this.sEchartsInstance.setOption(this.sChartOptions);
    }
  }

  ngOnDestroy() {
    if (this.interval) {
      clearInterval(this.interval);
    }
  }
  openHistData(index) {
    this.dialog.open(PersonContentComponent, {
      disableClose: true,
      autoFocus: false,
      width: '922px',
      data: {
        person: this.person,
        pageIndex:index
      }
    });
  }
}
